## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
# < edited by the ViSa Modpack Team >
## Implementaion of miscellaneous game functions

from CvPythonExtensions import *

import CvUtil
import CvGameUtils
import PyHelpers
import CvConfigParser

import CvActionButtonUtils

import ScreenInput
import CvScreenEnums
import CvEventInterface

import Popup as PyPopup



# globals
gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo
CvActionButtonUtils = CvActionButtonUtils.CvActionButtonUtils()

DIPLOMATIC_RELATIONS = gc.getGame().getMapRand().get(500,"Action") + 1000
START_INSURRECTION = DIPLOMATIC_RELATIONS+1
TRAIN_UNIT = DIPLOMATIC_RELATIONS + 2

# Change this to false if insurrections should not allow cities to flip to the
# player's civilization.
# Default value is true
g_bInsurrectionCanFlipCity = true

# Increase or decrease the value to change the base amount of time the 
# insurrection will last.
# Default value is 6
g_iBaseInsurrectionTime = 6

# Change this to false if the base insurrection time should be based on the
# player's cultural influence.
# Default value is true
g_bInsurrectionTimePlayerCultureBased = true


class CvViSaGameUtils(CvGameUtils.CvGameUtils):
	def __init__(self):
	
		global g_bInsurrectionCanFlipCity
		global g_iBaseInsurrectionTime
		global g_bInsurrectionTimePlayerCultureBased		

		config = CvConfigParser.CvConfigParser("ViSa_v3.ini")
		
		# Read the configuration values for the great statesman
		if(config != None):
			g_bInsurrectionCanFlipCity = config.getboolean("Great Statesman", "Insurrection Can Flip City", True)
			g_iBaseInsurrectionTime = config.getint("Great Statesman", "Base Insurrection Time", 6)
			g_bInsurrectionTimePlayerCultureBased = config.getboolean("Great Statesman", "Insurrection Time Player Culture Based", True)


	# This method is called when there is some type of action that wasn't handled.
	def cannotHandleAction(self,argsList):
		pPlot = argsList[0]
		iAction = argsList[1]
		bTestVisible = argsList[2]                
                
		# Handle the diplomatic relations button pressed action
		if(iAction == DIPLOMATIC_RELATIONS):
			self.__eventDiplomaticsRelationsPopup()

		# Handle the start insurrection button pressed action
		if(iAction == START_INSURRECTION):
			self.startInsurrection()
			
		# Handle if the Train Unit button pressed
		if(iAction == TRAIN_UNIT):
			objUnit = CyInterface().getHeadSelectedUnit()
			CvActionButtonUtils.startTrainingUnit(objUnit)
			
		return False


	# This method will handle the case where the improve diplomatic relations action button is pressed.
	def __eventDiplomaticsRelationsPopup(self): 
		player = gc.getActivePlayer()
		iPlayer = player.getID()
		
		popup = PyPopup.PyPopup(CvUtil.DIPLOMATIC_RELATIONS_POPUP, EventContextTypes.EVENTCONTEXT_ALL)
		popup.setHeaderString("Select a leader to improve diplomatic relations with:")

		# Go through all of the players in the game.
		for iLoopPlayer in range(gc.getMAX_PLAYERS()):

			# Only allow players that are alive, not the current active player or a minor civilization
			if (gc.getPlayer(iLoopPlayer).isAlive() and iLoopPlayer != iPlayer and not gc.getPlayer(iLoopPlayer).isBarbarian() and  not gc.getPlayer(iLoopPlayer).isMinorCiv()):

				# Add any players that have met the currently active player to the popup
				if (gc.getTeam(gc.getPlayer(iLoopPlayer).getTeam()).isHasMet(player.getTeam())):

					gc.getPlayer(iLoopPlayer).AI_setAttitudeExtra(iPlayer, 0)
					
					# Get the current player's attitude towards the active player
					strButtonText = str(gc.getAttitudeInfo(gc.getPlayer(iLoopPlayer).AI_getAttitude(iPlayer)).getDescription())
					
					strHelpText = str("Improve diplomatic relations with " + gc.getPlayer(iLoopPlayer).getName())
					
					# Get the information if the current player is at war with the currently active player
					if(gc.getTeam(gc.getPlayer(iLoopPlayer).getTeam()).isAtWar(player.getTeam())):
						strButtonText = strButtonText + " and at war"
						strHelpText = str("Make peace with " + gc.getPlayer(iLoopPlayer).getName())
						
					strButtonText = strButtonText + " with you."
					
					leaderHeadImage = str(gc.getLeaderHeadInfo( gc.getPlayer(iLoopPlayer).getLeaderType() ).getButton())					
					popup.addPythonButton( str(gc.getPlayer(iLoopPlayer).getName()), strButtonText, strHelpText, leaderHeadImage, iLoopPlayer, -1, true  )
					

		popup.launch(true)
		
	
	def	startInsurrection(self):
		
		activePlayer = gc.getActivePlayer()
		iActivePlayer = activePlayer.getID()
		
		statesmanList = PyPlayer(iActivePlayer).getUnitsOfType(gc.getInfoTypeForString("UNIT_STATESMAN"))
		
		selectedStatesman = None
		
		for statesman in statesmanList:
			if(statesman.IsSelected()):
				selectedStatesman = statesman
				break
				
		if(selectedStatesman == None):
			return
			
		targetPlot = selectedStatesman.plot()
		
		targetCity = targetPlot.getPlotCity()
		
		iTargetPlayer = targetPlot.getOwner()
		targetPlayer = gc.getPlayer(iTargetPlayer)
		
		iActivePlayerCityCulture = float(targetPlot.getCulture(iActivePlayer))
		iTargetPlayerCityCulture = float(targetPlot.getCulture(iTargetPlayer))
		iTotalCityCulture = float(targetPlot.countTotalCulture())
		iActivePlayerPercentCulture = int((iActivePlayerCityCulture/iTotalCityCulture) * 100)
		
		iInsurrectionTime = g_iBaseInsurrectionTime
		
		if(g_bInsurrectionTimePlayerCultureBased):
			iInsurrectionTime = int(iInsurrectionTime + ((iTotalCityCulture/iTargetPlayerCityCulture) * (0.1 * iActivePlayerCityCulture)))

		if(g_bInsurrectionCanFlipCity):
			iFlipChance = gc.getGame().getMapRand().get(int(iTotalCityCulture),"Great Statesman")
			#CyInterface().addImmediateMessage(str(iActivePlayerCityCulture) + ">=" + str(iFlipChance) + " = " + str(iActivePlayerCityCulture >= iFlipChance),"")
			if(iActivePlayerCityCulture >= iFlipChance):
				targetPlot.setOwner(iActivePlayer)
				return
		
		targetCity.changeOccupationTimer(iInsurrectionTime)

		strMessage = selectedStatesman.getNameNoDesc() + " has started an insurrection in " + targetCity.getName()
		
		# Inform the player that their great statesman has started an insurrection.
		CyInterface().addMessage(iActivePlayer, False, 0, strMessage, "", 0, gc.getUnitInfo(selectedStatesman.getUnitType()).getButton(), ColorTypes(0), targetCity.getX(), targetCity.getY(), True, True) 

		selectedStatesman.kill(true, iActivePlayer)


	# Resets the action button numbers
	def initActionButtonNumbers(self):
		global DIPLOMATIC_RELATIONS
		global START_INSURRECTION
		
		DIPLOMATIC_RELATIONS = gc.getGame().getMapRand().get(500,"Action")+1000
		START_INSURRECTION = DIPLOMATIC_RELATIONS+1
		TRAIN_UNIT = DIPLOMATIC_RELATIONS+2
		
